/**
 * 权限管理
 */
import { defineStore } from 'pinia';
import { useUserStore } from './user';

export const usePermissionStore = defineStore('permission', {
	state: () => ({
		comboList: [] as any, // 套餐数据
		selectedComboInfo: {} as any, // 选中套餐信息
		// 权限相关状态（从 main 迁移）
		filterUnPermissionConfig: [], // 过滤后的模块权限
		unPermissionConfig: [], // 原始权限配置
		moduleTabbar: [] as any, // 底栏权限数据
		moduleInfoAll: [] as any, // 模块菜单权限
		appModules: [], // 菜单数据
		activeModule: null as any,
		// activeModuleID: null, // 历史选中模块ID
		activeModuleStartType: true,
	}),
	actions: {
		/**
		 * 获取帐套套餐数据并触发权限加载
		 * @param request 请求实例
		 */
		async getAppComboInfoByAccountID({ request } : { request : any }) {
			const userStore = useUserStore();
			const permissionStore = usePermissionStore();

			const ret = await request({
				url: 'SelectActivatedModule',
				method: 'POST',
				data: { AccountID: userStore.UserInfo.Business }
			});
			console.log(ret);
			if (ret.status === 200) {
				this.comboList = ret.data.ds.map((item : any) => {
					return {
						...item,
						text: item.ModuleName,
						value: item.ModuleID,
					}
				});

				// 处理选中套餐逻辑
				if (this.comboList.length) {
					const storedCombo = this.selectedComboInfo;
					console.log(storedCombo);
					if (!uni.$utils.isEmpty(storedCombo)) {
						const parsedCombo = storedCombo;
						const findData = this.comboList.find(
							(item : any) => item.ModuleID === parsedCombo.ModuleID
						);
						this.selectedComboInfo = findData || this.comboList[0];
					} else {
						
						this.selectedComboInfo = this.comboList[0];
					}
					console.log(this.selectedComboInfo);
					// uni.setStorageSync("selectedComboInfo", JSON.stringify(this.selectedComboInfo));
				}

				// 调用权限模块加载菜单权限
				if (this.selectedComboInfo?.ModuleID) {
					await permissionStore.getAllMenuDataByCombo({
						request,
						moduleID: this.selectedComboInfo.ModuleID
					});
				}
			}
		},
		/**
		 * 根据模块名称过滤权限配置
		 * @param moduleName 模块名称
		 */
		getUnPermissionConfigInfo(moduleName : string) {
			this.filterUnPermissionConfig = this.unPermissionConfig.filter(
				(item : any) => item.ModuleName === moduleName
			);
		},

		/**
		 * 获取指定模块的角色权限
		 * @param params 请求参数
		 * @returns 权限数据Promise
		 */
		getAPPRoleColFunByRoleID({
			request,
			moduleName,
			moduleType
		} : {
			request : any;
			moduleName : string;
			moduleType : string;
		}) {
			return request({
				url: 'getAPPRoleColFunByRoleID',
				method: 'POST',
				data: { moduleName, moduleType }
			});
		},

		/**
		 * 根据套餐获取菜单和权限数据
		 * @param params 请求参数
		 */
		async getAllMenuDataByCombo({
			request,
			moduleID,
			option = 1
		} : {
			request : any;
			moduleID : string | number;
			option ?: any;
		}) {
			const userStore = useUserStore();
			return new Promise((resolve) => {
				request({
					url: 'platform_getAppModule',
					method: 'POST',
					data: {
						AccountID: userStore.UserInfo.Business,
						UserID: userStore.UserInfo.UserID,
						ModuleID: moduleID
					},
					success: (ret : any) => {
						if (ret.status === 200 && ret.data.ds.length) {
							const { ds, ds1, ds2 } = ret.data;
							const pagesByModule = new Map();

							// 预处理页面数据
							ds1.forEach((item : any) => {
								item.IsChecked = !!item.IsShortcut;
								if (!pagesByModule.has(item.APPType)) {
									pagesByModule.set(item.APPType, []);
								}
								pagesByModule.get(item.APPType).push(item);
							});

							// 构建模块树形结构
							ds.forEach((module : any) => {
								const modulePages = pagesByModule.get(module.ModuleID) || [];
								const treeTypeMap = new Map();

								modulePages.forEach((page : any) => {
									if (!page.IsTabbar) {
										const key = page.TreeType;
										if (!treeTypeMap.has(key)) {
											treeTypeMap.set(key, {
												treeType: key,
												treeTypeName: page.TreeTypeName,
												pages: []
											});
										}
										treeTypeMap.get(key).pages.push(page);
									}
								});

								module.shortcuts = modulePages.filter((p : any) => p.IsShortcut);
								module.treeTypes = Array.from(treeTypeMap.values());
								module.authPages = modulePages;
							});

							// 更新权限状态
							this.appModules = ds;
							this.unPermissionConfig = ds2 || [];
							console.log("菜单、权限获取完成");
						} else {
							this.appModules = [];
						}
						resolve(ret);
					}
				});
			});
		},
		// 根据模块ID获取对应模块菜单数据
		getAPPModulePages({ request, module } : {
			request : any;
			module : any;
		}) {
			let that = this;
			return new Promise((resolve, reject) => {
				const userStore = useUserStore();
				console.log(module);
				request({
					url: 'getAPPModulePages',
					method: 'POST',
					data: {
						UserID: userStore.UserInfo.UserID,
						APPType: module.ModuleID,

					},
					success: (ret : any) => {
						console.log(ret);
						if (ret.status == 200) {
							const data = ret.data.ds;
							const ds1 = ret.data.ds1;
							// 预先处理ds1，以APPFunID为键，值为对应的数组
							const ds1Map = new Map(ds1.map((row : any) => [row.APPFunID, [row]]).reduce((acc : any, [key, val] : any) => {
								acc.set(key, [...acc.get(key) || [], ...val]);
								return acc;
							}, new Map()));

							let organizedDataInfo = that.organizeByTreeTypeName(data, ds1Map);
							console.log("--------");
							that.moduleInfoAll = JSON.parse(JSON.stringify(organizedDataInfo));
							console.log(that.moduleInfoAll);

							let organizedData = organizedDataInfo.sort((a, b) => a.TreeType - b.TreeType);
							// 这里获取了模块以及页面的权限树，将 IsTabbar 为true的筛选出来，作为底部栏数据

							let TabbarData = organizedData.flatMap(item => item.Node.filter((row : any) => row.IsTabbar)).sort(
								(a, b) => a.APFunCode - b.APFunCode); // 对结果进行排序
							console.log(TabbarData);
							that.moduleTabbar = TabbarData;
							that.activeModule = module;
							// that.activeModuleID = APPType;
							// console.log(module);
							console.log(that.moduleInfoAll);


							resolve({ status: 200 })

						} else {
							reject(ret)
						}
					},
					fail: (err : any) => {
						reject(err)
					}
				})
			})
		},
		organizeByTreeTypeName(arr : any, ds1Map : any) {
			// 创建一个映射来按TreeType分组数据  
			const groupedData : any = {};

			arr.forEach((item : any) => {
				const treeType = item.TreeType;
				const treeTypeName = item.TreeTypeName; // 用于分组的键  

				if (!(treeTypeName in groupedData)) {
					groupedData[treeTypeName] = {
						TreeType: treeType, // 保留TreeType  
						APPType: item.appType, // 保留APPType
						Node: [],
					};
				}

				// 检查ds1Map中是否有匹配的APPFunID  
				if (ds1Map.has(item.APPFunID)) {
					groupedData[treeTypeName].Node.push({
						...item,
						IconApprove: ds1Map.get(item.APPFunID), // 如果需要，直接添加IconApprove  
					});
				} else {
					groupedData[treeTypeName].Node.push({
						...item,
						IconApprove: []
					});
				}
			});

			// 提取分组后的数据为数组，并可能按某种逻辑排序（这里不排序，因为TreeTypeName已经是分组键）  
			const sortedData = Object.entries(groupedData).map(([treeTypeName, group] : any) => ({
				TreeTypeName: treeTypeName,
				...group, // 展开分组对象，它包含TreeType, APPType, APPFunID, 和 Node 数组  
			}));

			return sortedData;
		}
	},
	persist: {
		key: 'permission-store',
		paths: [
			'comboList',
			'selectedComboInfo',
			'unPermissionConfig',
			'moduleInfoAll',
			'moduleTabbar',
			'appModules',
			'activeModule',
			// 'activeModuleID',
			'activeModuleStartType'
		]
	}
});